package controllers

import (
	"day01/models"
	beego "github.com/beego/beego/v2/server/web"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: password,
	}

	if err := models.DB.Create(&user).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    user,
		Message: "注册成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User

	if err := models.DB.Where("username = ?", username).Find(&user).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "用户不存在,请前往注册",
		}
		c.ServeJSON()
		return
	}

	if user.Password != password {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    user,
		Message: "登录成功",
	}
	c.ServeJSON()
	return
}
